#!/usr/bin/env python
#coding:utf-8
#autor:Qiweiwei
#python -m pip install --upgrade --force pip
#pip install setuptools==33.1.1
#pip install cm-api
import shlex
import subprocess
from smtplib import SMTP
from email import MIMEText
from email import Header
from cm_api.api_client import ApiResource,ApiException
host = ['192.168.1.44','192.168.130.000']
def ping(ip):
    ping_res = ''
    for host in ip:
        #print host
        cmd = "ping -c 1 %s" %(host)
        #print cmd
        args = shlex.split(cmd)
        try:
            subprocess.check_call(args,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            ping_res += "The server %s is up !\n" %(host)
        except:
            ping_res += "Failed to get ping %s!\n"  %(host)
    return ping_res

def ScanAws(args):
    res = ''
    for node in args:
        print node
        res +=  "===========================\n"
        api = ApiResource(node, 7180, version=1, username='admin', password='admin')
        for c in api.get_all_clusters():
            res += "You have checked %s \n"%(c.name)
            # if c.version == "CDH5":
            #   cdh5 = c
        for s in c.get_all_services():
            res += "    %s %s %s\n" % (s.name, s.serviceState, s.healthSummary)
        res += "===========================\n"
    return res
#ScanAws('54.223.144.22','54.222.242.143','192.168.130.60')

#定义主机 帐号 密码 收件人 邮件主题
smtpserver = 'smtp.exmail.qq.com'
sender = 'support@k2da.com.cn'
password = 'K2admin1217'
receiver = ('qishengjie@k2data.com.cn')
subject = u'CM环境巡检状态邮件'
From = u'运维'
To = u'AWS-suport-Team'
#定义日志文件位置
error_log = '/tmp/web_server_status.txt'
def send_mail(context):

    #定义邮件的头部信息
    header = Header.Header
    msg = MIMEText.MIMEText(context,'plain','utf-8')
    msg['From'] = header(From)
    msg['To'] = header(To)
    msg['Subject'] = header(subject + '\n')
    #连接SMTP服务器，然后发送信息
    smtp = SMTP(smtpserver)
    smtp.login(sender, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.close()
if __name__=='__main__':
    try:
        res = ScanAws(host)
        #send_mail(res)
    except Exception,e:
        res = ping(host)
        send_mail(res)
